/**
 * 
 */
//负责db操作的js文件
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/mydatabase');

var Schema = mongoose.Schema;
//定义联系人的模型结构
var Contacts = new Schema({
	name:String,
	number:String,
	address:String
});
mongoose.model('Contact',Contacts);

//var Contact = mongoose.model('Contact');
//var contact = new Contact();
//task.project = 'bikeshed';
//task.description = 'Paint the bikeshed red.';
//task.save(function(err){
//	if(err) throw err;
//	console.log("Task saved.");
//});
exports.add = function(name,number,address){
	var Contact = mongoose.model('Contact');
	var contact = new Contact();
//	var contact2 = new Contact();
//	var contact2;
//	contact2.save();
	contact.name = name;
	contact.number = number;
	contact.address = address;
	
	contact.save(function(err){
		if(err) 
			throw err;
		console.log("contact saved");
	});
	
	
	
	console.log("document added");
};
//直接将一个对象插入数据库
exports.addObj = function(contactObj){
	
}
//根据id删除一条document
//删除数据这里有问题，不过先过了，先不管。---问题已经解决，使用Contact.remove()方法，而不用Contact.findById先查再删
exports.delByname = function(dname){
	
	var Contact = mongoose.model('Contact');
//	Contact.findById(id,function(err,contact){
//		contact.remove();
//	});//这里在redmine上的说明文档中写的删除操作，在这报错，下面的代码是查了mogoose的API文档之后写的，经测试好用
	
//	Contact.remove({ _id: id }, function (err) {
//		if(err)
//			throw err;
////		mongoose.disconnect();
//		
//	});
	Contact.remove({ name: dname }, function (err) {
		if(err)
			throw err;
		
	});
	
	console.log("document deleted");
}
/**/
//更新的时候需要_id这个属性（在mongoDB中会自动生成）
exports.updateNameById = function(id,uname){
	var Contact = mongoose.model('Contact');
	Contact.update( {_id:id}, {name:uname}, {multi:false},
			function(err,rows_updated){
				if(err) throw err;
				console.log('Updated');
		});
	
	
	
	console.log("document updated");
}

//这里查找暂时只能通过姓名查找
exports.findByName = function(name){
	var Contact = mongoose.model('Contact');
	var contactList = Contact.find({'name':name},function(err,contacts){
		for(var i=0;i<contacts.length;i++){
//			console.log(contacts[i]);
			console.log('ID'+ contacts[i]._id);
			console.log(contacts[i].name+" "+contacts[i].number+" "+contacts[i].address);
//			mongoose.disconnect();
		}
	});
	
	console.log("document finded");
	return contactList;
}

exports.findAll = function(){
	var Contact = mongoose.model('Contact');
	/*var query = Contact.find({}, function(err,contacts){
		for(var i=0;i<contacts.length;i++){
			console.log('ID'+ contacts[i]._id);
			console.log(contacts[i].name+" "+contacts[i].number+" "+contacts[i].address);
//			mongoose.disconnect();
		}
	});*/
	var query = Contact.find({});
	return query;
	console.log("document findAll");
}